<?php

namespace app\admin\controller\inventory;

use app\admin\model\inventory\Kc;
use app\common\controller\Backend;
use think\Db;
use think\Exception;
use addons\crontab\controller\Pda;
use app\admin\model\AuthRule;
use app\admin\model\inventory\Procure;
use app\admin\model\inventory\Material;
use app\common\model\Inventory;
use app\admin\model\outhouse\TpdjList;
use app\admin\model\outhouse\Tpdj;
use app\admin\model\outhouse\CheckVouch;
use app\admin\model\outhouse\CheckVouchList;
use app\api\controller\Wms;
use PDOException;
use app\admin\model\inventory\Wmskc;
use think\Request;
use think\Log;
use app\admin\model\inventory\Temporary as InventoryTemporary;
use app\admin\model\inventory\MaterialListView;
/**
 * 入库/退货单临时管理
 *
 * @icon fa fa-circle-o
 */
class Temporary extends Backend
{

    /**
     * Temporary模型对象
     * @var \app\admin\model\inventory\Temporary
     */
    protected $model = null;
    protected $kcmxModel = null;
    protected $u8fitemModel = null;
    protected $pdaBillModel = null;
    protected $procureModel = null;
    protected $materialModel = null;
    protected $about_in_type_arr = [1,3,5,6,10,14,16];
    protected $repeat_in_type_arr = [1,6,10,14,16];
    protected $repeat_out_type_arr = [2,7,11,15];
    protected $setting_limit_time  = 2;//复核间隔时间x秒
    public $tocheck_auth_by_person = [8];//验证人工审核的单
    public $tocheck_auth_str = [
        8 => '/pages/stockbill/listfh?type=16'
    ];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\inventory\Temporary;
        $this->pdaBillModel = new \app\common\model\PdaBill;
        $this->procureModel = new Procure();
        $this->materialModel = new Material();
        $this->kcmxModel = new \app\admin\model\outhouse\Kcmx;
        
        //$this->u8fitemModel = new \app\admin\model\information\U8fitem;
        
        $this->view->assign("orderListList", $this->model->getOrderListList());
        $this->view->assign("groundingListList", $this->model->getGroundingListList());
        $this->view->assign("statusListList", $this->model->getStatusListList());
        $this->view->assign("passStatusListList", $this->model->getPassStatusListList());
        $this->view->assign("shelvesTypeList", $this->model->getShelvesTypeList());

        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);

        // $detail = db('temporary')->where([
        //     'order_code' => 'P04SEOUT240110001'
        // ])
        // ->field('number inv_number,cBatch,quantity fqty,shelves_id')
        // ->select();
        // $type = 15;
        // $main['source_code'] = 'AABB';
        
        //  //20240108针对pda提交上来的销售订单，同物料求和
        // $sell_temp_arr = [];
        // if($type==15){
        //     $sell_temp_inv_arr = array_column((array)$detail,'inv_number');//提交上来的物料id数组
        //     $sell_temp_inv_arr = array_unique($sell_temp_inv_arr);

        //     foreach ($detail as $kk=>$vv){
        //         if(isset($sell_temp_arr[$vv['inv_number'].'_'.$vv['cBatch']])){
        //             $sell_temp_arr[$vv['inv_number'].'_'.$vv['cBatch'].'_'.$vv['shelves_id']] += $vv['fqty'];
        //         }else{
        //             $sell_temp_arr[$vv['inv_number'].'_'.$vv['cBatch'].'_'.$vv['shelves_id']] = $vv['fqty'];
        //         }
        //     }
            
        //     asort($sell_temp_arr);//小-》大
        //     dump($sell_temp_arr);
        //     //得到所有提交上来的发货通知单明细
        //     $sell_order_arr = collection(MaterialListView::where([
        //         'material_code' => $main['source_code'],
        //         'inventory_number' => ['IN',$sell_temp_inv_arr],
        //         'status' => 1
        //     ])
        //     ->field('auto_id,row_id,inventory_number,no_quantity,fCoefficient')
        //     ->select())
        //     ->toArray();
        //     dump($sell_order_arr);
        //     $deal_data = [];
        //     if($sell_temp_arr){
        //         foreach($sell_temp_arr as $sk=>&$total_fqty){
        //             $sk_arr = explode('_',$sk);
                   
        //             foreach($sell_order_arr as &$sell_order){
        //                 if($sell_order['no_quantity']>0){
        //                     if($sell_order['inventory_number']==$sk_arr[0]){
        //                         //同个物料,插入临时表
        //                         //$sell_order['no_quantity']
        //                         $thisqty = $sell_order['no_quantity'];
        //                         $total_fqty -= $sell_order['no_quantity'];
                                
        //                         if($total_fqty<0){
        //                             $thisqty = $sell_order['no_quantity']+$total_fqty;
        //                             $total_fqty = 0;
        //                             $sell_order['no_quantity'] -= $thisqty;
                                    
        //                         }else{
        //                             $sell_order['no_quantity'] = 0;
        //                         }

        //                         if($thisqty){
        //                             $deal_data[] = [
        //                                 'auto_id' => $sell_order['auto_id'],
        //                                 'row_id' => $sell_order['row_id'],
        //                                 'cBatch'=>$sk_arr[1],
        //                                 'shelves_id'=>$sk_arr[2],
        //                                 'fqty'=>$thisqty,
        //                                 'auxfqty' => $thisqty/$sell_order['fCoefficient'],
        //                                 'inv_number' =>$sell_order['inventory_number']
        //                             ];
        //                             //$this->toAddTemp($sell_order,$main,['cBatch'=>$sk_arr[1],'fqty'=>$thisqty]);
        //                         }
        //                     }
        //                 }
        //             }
        //             if($total_fqty<=0){
        //                 continue;
        //             }
        //         }
        //     }
        //     array_multisort(array_column($deal_data, 'row_id'),SORT_ASC,$deal_data);
        //     dump($deal_data);exit;
        // }
    }


    public function index()
    {
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
        
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        $op = $this->request->get("op", '', 'trim');
        $op = (array)json_decode($op, true);
        $filter = $this->request->get("filter", '');
        $where2 = [];
        if($filter){
            $filter=urldecode($filter);
            $filter=json_decode($filter,TRUE);
            if(isset($filter['order_list_tab'])){
                switch($filter['order_list_tab']){
                    case 1://入库相关
                        $where2 ['order_list'] = ['IN',$this->about_in_type_arr];
                        break;
                    case 2://出库相关
                        $where2 ['order_list'] = ['IN',[2,4,7,11,12,15]];
                        break;
                    case 3://调拨
                        $where2 ['order_list'] = ['IN',[8]];
                        break;
                    case 4://盘点
                        $where2 ['order_list'] = ['IN',[9]];
                        break;
                    case 5:
                        $where2 ['order_list'] = ['NEQ','not null'];
                        break;
                }
                unset($filter['order_list_tab'],$op['order_list_tab']);
            }
            if(isset($filter['createtime'])){
                $createtime_arr = explode(' - ', $filter['createtime']);
                $where2['a.createtime'] = [
                    'BETWEEN',$createtime_arr
                ];
                unset($filter['createtime'],$op['createtime']);
            }
            $this->request->get(["filter"=>json_encode($filter),'op'=>json_encode($op)]);
        }

        setParam([
            'b.number' => 'number',
            'b.name' => 'name',
            'a.cBatch' => 'cBatch',
            'c.name' => 'warehouse_name',
            'd.name' => 'shelves_name'
        ]);
        
        $this->searchFields = 'b.name,b.number,b.specification,b.unit,c.name,d.name,d.number,a.source_code,a.order_code,a.b_remark,a.cBatch';
        
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        $list = $this->model->alias('a')
        //->with(['warehouse','shelves'])
        ->join('Inventory b','b.number=a.number','left')
        ->join('Warehouse c','c.id=a.warehouse_id','left')
        ->join('Shelves d','d.id=a.shelves_id','left')
        ->field('a.*,b.name,b.specification,b.unit,b.store_unit,c.name warehouse_name,d.name shelves_name,d.type shelves_type')
        ->where($where)
        ->where($where2)
        ->order($sort, $order)
        ->paginate($limit);
        
        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }

    /**
     * 处理PDA单据
     */
    public function setting($auto_order_codes = [])
    {
        //自动处理单据
        if($auto_order_codes){
            $order_codes = $auto_order_codes;
        }else{
            $param = $this->request->param();

            if(!$param['id']){
                exception('请选择单据');
            }
            
            $status = 0;//待处理单据
            $repeatKis = false;//不重试kis回写
            if(isset($param['flag'])&&$param['flag']=='repeat'){
                $status = 1;//待处理单据
                $repeatKis = true;
            }
            
            //按整单处理
            $order_codes = $this->model::where([
                'id' => ['in',$param['id']],
                'status' => $status 
            ])
            ->group('order_code')
            ->column('order_code');
        }
        
        Db::startTrans();
        try {
            $pda = new Pda();
            foreach ($order_codes as $k=>$order_code){
                $pdaBill = $this->pdaBillModel::where([
                    'FBillNo' => $order_code,
                    'status' => 1
                ])->find();
                
                if(!$pdaBill){
                    exception('pda原始单据丢失');
                }
                $bill = json_decode($pdaBill->main,true);
                /*$billentry = json_decode($pdaBill->billentry,true); */
                
                $temp_arr = db('temporary_view')->where([
                    'order_code' => $order_code,
                    'status' => $status
                ])
                ->select();
                
                if(!$temp_arr){
                    //exception('暂无待处理单据');
                    //处理过的，还勾选的，则跳过
                    continue;
                }

                //20241221 新增内外销方式录入
                foreach($temp_arr as $temp_row){
                    if(!$temp_row['status']){
                        if($temp_row['order_list']==14&&
                        !$temp_row['sell_in_out']&&
                        stripos('mesWB',$temp_row['source_code'])==0){
                            //mes外包进来的产品才需要设置销售方式
                            $this->error("请先设置是否自营出口");
                        }
                    }
                    
                    //20250822 验证是否有复核权限
                    if(config('site.allot_to_check')){
                        if(in_array($temp_row['order_list'],$this->tocheck_auth_by_person)){
                            $auth_str = $this->tocheck_auth_str[$temp_row['order_list']];
                            if(AuthRule::get(['name'=>$auth_str])){
                                //有存在这个权限串，才判断权限
                                $rules = $this->auth->getRuleList();
                                if(!in_array($auth_str,$rules)){
                                    exception('暂无权限复核单据');
                                }
                            }
                        }
                    }
                }
                
                //盘点单据,判断有无其他单据未处理，有则优先处理其他
                if($temp_arr[0]['order_list'] == 9){
                    $check = db('temporary')->where([
                        'order_list' => ['NEQ',9],
                        'status' => $status
                    ])
                    ->find();
                    
                    if($check){
                        $this->error("存在其他单据待复核,请复核后,再执行盘点");
                    }
                }

                //20250305
                /*if (isset($_SESSION['last_submit_time'])
                && 
                time() - $_SESSION['last_submit_time'] < $this->setting_limit_time) {
                    Log::error('2秒内重复提交2次');
                    $this->error('提交过于频繁，请稍后再试');
                }*/

                //统一由一个地方调用函数处理
                $pda->dealTempData($temp_arr,$pdaBill->pctype,$repeatKis);
                
                //20250305
                //$_SESSION['last_submit_time'] = time(); 

                //新增，操作数量和库存明细数量比对，因为有发现一个情况，操作的pda单据数量，和入库明细数量不一致。
                //1 10 6 3 5 14收货，直接上架，采购退回 直接入 引源单入 产品入库
                $result = '';
                if(in_array($temp_arr[0]['order_list'], $this->about_in_type_arr)){
                    $kcmx_in_nums = $this->kcmxModel::where([
                        'code' => $order_code,
                        'type' => 1,//入
                    ])->count();
                    $kcmx_out_nums = $this->kcmxModel::where([
                        'code' => $order_code,
                        'type' => 0,//出
                    ])->count();
                    $result = "执行成功:".count($temp_arr);//."【入:{$kcmx_in_nums},出:{$kcmx_out_nums}】";
                }
                
                //更新为已处理状态
                $this->model::where('order_code',$order_code)->update([
                    'status' => 1,
                    'result'=> $result
                ]);
            }
            Db::commit();
            $this->success();
        }catch (Exception $e){
            Db::rollback();
            
            //特殊提示，不关闭订单,不在数组里，才需要关闭单据
            $spe_tip_arr = [
                '请先编辑当前管理员对应的U8用户,再复核',
                '暂时找不到对应入库任务,请稍后再试',
                '调KIS-API返回异常,请稍后再试',
                '调KIS-API网络异常,请稍后再试',
                'WMS配置缺失',
                '该单据未质检通过,请先质检',
                '暂无权限复核单据'
            ];

            if(!in_array($e->getMessage(), $spe_tip_arr)&&!$repeatKis){
                //更新为关闭状态
                $this->model::where('order_code',$order_code)->update([
                    'status' => 2,
                    'result' => '处理失败,'.$e->getMessage()
                ]);
            }

            //跟踪日志，顺便打印出错误地方
            Log::error('错误：'.$e->getMessage().PHP_EOL.$e->getTraceAsString());

            //20250305
            //$_SESSION['last_submit_time'] = time(); 
            $this->error('处理失败,'.$e->getMessage());
        }
    }

    public function edit($ids = null)
    {
        $row = $this->model->where(['id'=>$ids])->find();
        if($this->request->isPost()){
            $params = $this->request->post("row/a");
            if($row->status){
                $this->error('该单据已被处理，不能修改');
            }
            $row->allowField(true)->save($params);
            $this->success();
        }

        $this->assign('row',$row);
        return $this->fetch();
    }
    
    public function view($ids = null)
    {
        $ids = $this->request->request('ids',0);
        if(!$ids){
            exception('参数错误');
        }
        
        $row = $this->model::where(['id'=>$ids])->find();
        $tpstatus = $row->status;
        $page = '';
       
        if($this->request->isPost()){
            //提交修改20241221
            if($row['order_list'] == 14){
                $params = $this->request->post('row/a');
                if(empty($params['sell_in_out'])){
                    $this->error('销售方式不能为空');
                }

                $this->model->update([
                    'sell_in_out'=>$params['sell_in_out']
                ],[
                    'order_code'=>$params['order_code']
                ]);
                $this->success('修改成功');
            }

            //提交修改,是领料出库和直接出库，才进入
            if($row['order_list'] == 2 || $row['order_list'] == 11|| $row['order_list'] == 7){
                $params = $this->request->post('row/a');
                $basic_json = $params['basic'];
                $basic_arr = json_decode($basic_json, true);
                if(empty($params['cRdCode'])){
                    $this->error('出库类别不能为空');
                }
                
                /*if (!$row['cDepCode']||!is_numeric($row['cDepCode'])){
                    $this->error('部门编码为空,请核实');
                }*/
                
                foreach ($basic_arr as $item){
                    if (!isset($item['cItem_class'])||!isset($item['cItemCode'])){
                        $this->error('请选择项目');
                    }
                    if (!$item['cItem_class']||!$item['cItemCode']){
                        $this->error('请选择项目');
                    }
                    $this->model->update([
                        'cItem_class'=>$item['cItem_class'],
                        'cItemCode'=>$item['cItemCode'],
                        'cName'=>$item['cName'],
                        'cItemCName'=>$item['cItemCName'],
                        'cRdCode'=>$params['cRdCode'],
                        'cRdCodeName'=>$params['cRdCodeName'],
                        //'cDepCode'=>$row['cDepCode']
                    ],[
                        'id'=>$item['id']
                    ]);
                }
                $this->success('修改成功');
            }
        }
        
        if($row['order_list'] == 8){
            //调拨
            $tp = new Tpdj();
            $tplist = new TpdjList();
            $code = $row->order_code;
            $u8username = $row->u8username;
            $temp_status = $row->status;
            
            $row = $tp->with(['wareHouse','changeWareHouse'])->where('code',$code)->find();
            if(!$row){
                exception('找不到调拨单');
            }
            $row->u8username = $u8username;
            $row->temporary_id = $ids;
            $row->status = $temp_status;
            
            $list = $tplist->alias('a')
            ->join('Inventory b','b.number=a.cInvCode','left')
            ->join('Shelves d','d.id=a.shelves_id','left')
            ->join('Shelves e','e.id=a.shelves_change_id','left')
            ->field('a.tp_iQuantity,b.number,d.name shelves_name,a.cBatch,
            e.name to_shelves_name,d.type shelves_type,e.type to_shelves_type,
            b.name,b.specification,b.unit,b.warehouse_name tj_warehouse_name,
            b.shelves_name tj_shelves_name,b.store_unit,a.tp_iQuantity/b.fCoefficient store_quantity')
            ->where([
                'code' => $code
            ])
            ->select();
            $page = 'tpview';
        }else if($row['order_list'] == 9){
            //盘点
            $vouch = new CheckVouch();
            $vouchlist = new CheckVouchList();
            $code = $row->source_code;
            $u8username = $row->u8username;
            $temp_status = $row->status;
            
            $row = $vouch->with(['wareHouse'])->where('code',$code)->find();
            if(!$row){
                exception('找不到盘点单');
            }
            $row->u8username = $u8username;
            $row->temporary_id = $ids;
            $row->status = $temp_status;
            
            $list = $vouchlist->alias('a')
            ->join('Inventory b','b.number=a.cInvCode','left')
            ->join('Shelves d','d.id=a.shelves_id','left')
            ->field('a.iQuantity,a.iAdInQuantity,a.iAdOutQuantity,a.kc_quantity,
            a.duringIn,a.duringOut,a.iCVCQuantity,b.number,d.name shelves_name,
            d.type shelves_type,b.name,b.specification,b.unit,a.inv_id,a.cBatch')
            ->where([
                'code' => $code,
                'temporary_id' => $ids,
                'a.deletetime' => null
            ])
            ->order('a.scan_flag desc,a.cInvCode')
            ->select();
            $page = 'ckview';
        }else{
            $list = $this->model->alias('a')
            ->join('Inventory b','b.number=a.number','left')
            ->join('Warehouse c','c.id=a.warehouse_id','left')
            ->join('Shelves d','d.id=a.shelves_id','left')
            ->field('a.id,a.quantity,a.b_remark,a.number,c.name warehouse_name,a.cBatch,
d.name shelves_name,d.type shelves_type,b.name inv_name,b.specification inv_specification,
b.unit inv_unit,b.warehouse_name tj_warehouse_name,b.shelves_name tj_shelves_name,a.order_list,
a.cItem_class,a.cItemCode,a.cName,a.cItemCName,b.store_unit,a.store_quantity')
            ->where([
                'order_code' => $row->order_code
            ])
            ->select();
            $cItem_class = array_column($list, 'cItem_class');
            $this->assign('cItemClassArr',$cItem_class);
            
            if($row['order_list']==12){
                $pdaBill = $this->pdaBillModel::where([
                    'FBillNo' => $row->order_code,
                    'status' => 1
                ])->find();
                if(!$pdaBill){
                    exception('pda原始单据丢失');
                }
                $bill = json_decode($pdaBill->main,true);
                //$row['to_shelves_name'] = $bill['to_shelves_name'];
            }
            
        }
        
        $this->assign('tpstatus',$tpstatus);
        $this->assign('row',$row);
        $this->assign('list_json',json_encode($list));

        $this->view->assign('sellInOutList',$this->model->getSellInOutList());
        
        //$this->view->assign("getCItemList", $this->u8fitemModel::getCItemList());
        //$this->view->assign("rdStyleList", U8rdstyle::getList());
        return $this->fetch($page);
    }

    /**
     * 删除
     *
     * @param $ids
     * @return void
     * @throws DbException
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     */
    public function del($ids = null)
    {
        if (false === $this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ?: $this->request->post("ids");
        if (empty($ids)) {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }
        $pk = $this->model->getPk();
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        
        $delsFlag = $this->request->post("dels",0);
        if($delsFlag){
            //整单删除
            $order_code_arr = $this->model->where($pk, 'in', $ids)
            ->group('order_code')
            ->column('order_code','id');
            
            //所有明细记录
            $list = $this->model->where([
                'order_code' => ["IN",$order_code_arr]
            ])->select();
        }else{
            //删除明细
            $list = $this->model->where($pk, 'in', $ids)->select();
        }
        
        $order_type_arr = [3,4,8,9];//其他入3 其他出4 调拨8 盘点9
        
        $count = 0;
        Db::startTrans();
        
        $procure_reload = false;//采购订单重载
        $material_reload = false;//领料单重载
        $material_code_arr = [];//单号
        try {
            foreach ($list as $k=>$item) {
                if($item->status==1){
                    //已处理的单，判断u8有无存在，不存在则证明被删，则可以删，反之不能删
                    $this->model::checkU8ToDeleteFlag($item->id);
                }
            }
            
            $del_order_code_arr = [];
            foreach ($list as $k=>$item) {
                $order_list = $item->order_list;
                if($order_list==1||$order_list==14){
                    $procure_reload = true;
                }
                
                //其他特殊单据
                if(in_array($order_list, $order_type_arr)){
                    if($order_list == 3){
                        db('rdinrecord_list')->where([
                            'code' => $item->order_code,
                            'row_id' => $item->row_id
                        ])->delete();
                        if($k==0&&$delsFlag){
                            //删除表头
                            db('rdinrecord')->where([
                                'code' => $item->order_code
                            ])->delete();
                        }
                    }
                    if($order_list == 4){
                        db('rdoutrecord_list')->where([
                            'code' => $item->order_code,
                            'row_id' => $item->row_id
                        ])->delete();
                        if($k==0&&$delsFlag){
                            //删除表头
                            db('rdoutrecord')->where([
                                'code' => $item->order_code
                            ])->delete();
                        }
                    }
                    if($order_list == 8){
                        //删除表头
                        db('tpdj')->where([
                            'code' => $item->order_code
                        ])->delete();
                        //删除表体
                        db('tpdj_list')->where([
                            'code' => $item->order_code,
                        ])->delete();
                    }
                    if($order_list == 9){
                        //对有复核的单，才恢复
                        if($item->status==1){
                            //恢复对应的盘点单数量和恢复未扫描状态
                            /*db('check_vouch_list')->where([
                                'code' => $item->source_code,
                                'scan_flag'=>1,
                                'temporary_id' => $item->id
                                //'cInvCode'=>$row['inv_number'],
                                //'shelves_id' => $row['shelves_id']
                            ])->update([
                                'iAdInQuantity' => 0,
                                'iAdOutQuantity' => 0,
                                'iCVCQuantity' => 0,
                                'scantime' => null,
                                'scan_flag' => 0
                            ]);*/
                        }
                    }
                }
                
                if($procure_reload){
                    //采购订单，要更新本地源单入库数,删除之前
                    $this->procureModel->updateProducedata($item->source_code,$item->auto_id,$item);
                }

                $count += $item->delete();
                
                if($order_list==12||$order_list==15){//拣货、销售出库
                    $material_reload = true;
                    //领料订单，要更新本地源单出库数 得上面删除后 在统计才准
                    $this->materialModel->getMaterialData($item->source_code);
                }
                
                if($item->status==1){
                    //恢复库存
                    /*if($order_list==8||$order_list==9){
                        //调拨、盘点，只有1条记录，所以根据单号，去取全部库存记录
                        Wmskc::deleteWmskcByPdaBillCode($item->order_code);
                    }else{
                        Wmskc::deleteWmskcByPdaBillCode($item->order_code);
                    }*/
                    $del_order_code_arr[] = $item->order_code;
                }
                
                db('pda_bill')->where([
                    'FBillNo' => $item->order_code
                ])->delete();
            }
            
            //多单删除，循环删
            if($del_order_code_arr){
                $del_order_code_arr = array_unique($del_order_code_arr);
                foreach ($del_order_code_arr as $order_code){
                    Wmskc::deleteWmskcByPdaBillCode($order_code);
                }
            }
            
            if($material_reload){
                //领料订单，要更新本地源单出库数
                //$this->materialModel->getMaterialData('','',3);
            }
            
            Db::commit();
        } catch (PDOException|Exception $e) {
            Db::rollback();
            if(stripos($e->getMessage(),'code rownum unigue')>0){
                $this->error('请先删除任务，再删PDA单据');
            }
            Log::error('删除单据错误：'.$e->getMessage().PHP_EOL.$e->getTraceAsString());
            $this->error($e->getMessage());
        }

        if ($count) {
            $this->success();
        }

        $this->error(__('No rows were deleted'));
    }

    //批量更新
    public function multi($ids = null)
    {
        $params = $this->request->param('params');
        if(isset($params)){
            //不管关闭、反关闭，存在已复核的单，都无法操作
            if(InventoryTemporary::where([
                'id' => ['IN',$ids],
                'status' => 1
            ])
            ->value('id')){
                $this->error('存在已复核的复核，请核实');
            }
        }
        
        parent::multi();
    }
}